local base = _G
local math = base.math
module("gui")

ScrollbarG = {}
ScrollbarGMT = { __index = ScrollbarG }

base.setmetatable(ScrollbarG, { __index = ContainerG })

ScrollbarG.create = function(x, y, width, height, segments, horizontal, mt)
  local self = Container(x, y, width, height, mt or ScrollbarGMT)

  self.horizontal = horizontal

  self.up = Arrow(0, 0, width, height, "up")
  self.down = Arrow(0, 0, width, height, "down")
  self.slider = Slider(0, 0, width, height, segments, horizontal)
  self:update_dimensions()
  
  self.up.on_click = function(up)
    self.slider:set_value(self.slider.value - 1)
  end
  self.down.on_click = function(down)
    self.slider:set_value(self.slider.value + 1)
  end

  self:add_child(self.up)
  self:add_child(self.down)
  self:add_child(self.slider)

  return self
end

ScrollbarG.destroy = function(self)
  self.slider = nil
  self.up = nil
  self.down = nil
  self.horizontal = nil
  ContainerG.destroy(self)
end

ScrollbarG.key_command = function(self, key, ctrl, shift)
  self.slider:key_command(key, ctrl, shift)
end

ScrollbarG.wheel_move = function(self, z)
  self.slider:wheel_move(z)
end

ScrollbarG.update_dimensions = function(self)
  -- resize child nodes
  local up, down, slider = self.up, self.down, self.slider
  if self.horizontal == true then
    local w, h = math.min(self.height*2, 24), self.height
    if w*2 + 12 >= self.width then
      w = self.width/2 - 1
    end
    up.direction = "left"
    up:set_position(0, 0)
    up.width, up.height = w, h
    down.direction = "right"
    down:set_position(self.width - w, 0)
    down.width, down.height = w, h
    slider:set_position(w + 1, 0)
    slider:set_size(self.width - w*2 - 2, self.height)
    slider.node.visible = (slider.width > 12)
  else
    local w, h = self.width, math.min(self.width*2, 24)
    if h*2 + 12 >= self.height then
      h = self.height/2 - 1
    end
    up.direction = "up"
    up:set_position(0, 0)
    up.width, up.height = w, h
    down.direction = "down"
    down:set_position(0, self.height - h)
    down.width, down.height = w, h
    slider:set_position(0, h + 1)
    slider:set_size(self.width, self.height - h*2 - 2)
    slider.node.visible = (slider.height > 12)
  end
end

ScrollbarG.update = function(self, dt)
  ContainerG.update(self, dt)
  self:update_dimensions()
  -- todo: don't update all the time
  --self:redraw(dt)
end

Scrollbar = ScrollbarG.create